package org.batch.config.batch.item.writer;

import org.batch.entity.Trading;
import org.batch.service.business.TradingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;

/**
 * 批处理数据库持久化MySQL
 *
 * @author LiKun
 * @date 2021/9/28 18:41
 */
@Component
public class TradingJdbcWriter implements ItemWriter<Trading> {
    private static final Logger logger = LoggerFactory.getLogger(TradingJdbcWriter.class);

    @Resource
    private TradingService tradingService;

    @Override
    public void write(List<? extends Trading> list) throws Exception {
        list.stream().collect(groupingBy(Trading::getAccount, toList())).forEach((key, value) -> {
            try {
                tradingService.batchDealTrading(key, (List<Trading>) value);
            } catch (Exception e) {
                logger.info("批处理写入数据出错：id = {}，values = {}，原因 = {}", key, value, e.getMessage());
                e.printStackTrace();
            }
        });
    }
}
